import React, {useState} from 'react';
import {Button, Card, Col, Input, message, Row, Select, Space, Statistic, Tag} from 'antd';
import {AimOutlined, CheckCircleOutlined, ExportOutlined, ReloadOutlined, SearchOutlined} from '@ant-design/icons';
import DataTable from '../../components/DataTable/DataTable';
import {matchingAPI} from '../../services/api';
import {MATCHING_STATUS} from '../../utils/constants';

const {Option} = Select;

const MatchingPage = () => {
    const [dataId, setDataId] = useState('');
    const [matchingResults, setMatchingResults] = useState([]);
    const [matchTable, setMatchTable] = useState([]);
    const [loading, setLoading] = useState(false);
    const [selectedResult, setSelectedResult] = useState(null);
    const [statistics, setStatistics] = useState({
        totalMatches: 0,
        matchedRoutes: 0,
        matchedShipments: 0,
        avgMatchScore: 0
    });

    // 获取匹配结果数据
    const fetchMatchingResults = async (currentDataId) => {
        if (!currentDataId) {
            message.warning('请输入数据ID');
            return;
        }

        try {
            setLoading(true);

            // 根据dataId获取匹配详情
            const response = await matchingAPI.getDetailsByDataId(currentDataId);

            // response已经是data部分，确保是数组
            const details = Array.isArray(response) ? response : [];

            setMatchingResults(details);
            setMatchTable(details);

            // 计算统计数据
            const matchedDetails = details.filter(d => d.match_status === 1);
            const stats = {
                totalMatches: details.length,
                matchedRoutes: new Set(matchedDetails.map(d => d.route_id)).size,
                matchedShipments: matchedDetails.length,
                avgMatchScore: details.length > 0 ? (matchedDetails.length / details.length * 100) : 0
            };
            setStatistics(stats);

            message.success(`匹配结果加载成功，共 ${details.length} 条记录`);
        } catch (error) {
            console.error('获取匹配结果失败:', error);
            message.error('获取匹配结果失败: ' + (error.message || '未知错误'));
            setMatchingResults([]);
            setMatchTable([]);
            setStatistics({
                totalMatches: 0,
                matchedRoutes: 0,
                matchedShipments: 0,
                avgMatchScore: 0
            });
        } finally {
            setLoading(false);
        }
    };

    // 处理数据ID搜索
    const handleSearch = () => {
        fetchMatchingResults(dataId);
    };

    // 处理匹配结果选择
    const handleResultSelect = (result) => {
        setSelectedResult(result);
    };

    // 处理刷新
    const handleRefresh = () => {
        if (dataId) {
            fetchMatchingResults(dataId);
        }
    };

    // 处理数据导出 - 简化导出字段
    const handleExport = () => {
        const data = matchingResults.map(detail => ({
            '匹配详情ID': detail.id,
            '匹配结果ID': detail.match_result_id,
            '货物ID': detail.shipment_id,
            '路线ID': detail.route_id || 'Self',
            '匹配状态': detail.match_status === 1 ? '已匹配' : '未匹配',
            '数据ID': detail.data_id
        }));

        const csvContent = [
            Object.keys(data[0]).join(','),
            ...data.map(row => Object.values(row).join(','))
        ].join('\n');

        const blob = new Blob([csvContent], {type: 'text/csv;charset=utf-8;'});
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = `matching_results_${new Date().toISOString().split('T')[0]}.csv`;
        link.click();

        message.success('匹配结果导出成功');
    };

    // 获取状态颜色
    const getStatusColor = (status) => {
        const statusConfig = MATCHING_STATUS[status?.toUpperCase()];
        return statusConfig?.color || 'default';
    };

    // 表格列配置 - 根据MatchDetail数据结构优化显示
    const columns = [
        {
            title: '匹配详情ID',
            dataIndex: 'id',
            key: 'id',
            width: 80,
            sorter: (a, b) => a.id - b.id
        },
        {
            title: '货物ID',
            dataIndex: 'shipment_id',
            key: 'shipment_id',
            width: 100
        },
        {
            title: '路线ID',
            dataIndex: 'route_id',
            key: 'route_id',
            width: 100,
            render: (routeId) => routeId || <Tag color="blue">Self</Tag>
        },
        {
            title: '匹配状态',
            dataIndex: 'match_status',
            key: 'match_status',
            width: 80,
            render: (status) => (
                <Tag color={status === 1 ? 'green' : 'red'}>
                    {status === 1 ? '已匹配' : '未匹配'}
                </Tag>
            )
        },
        {
            title: '匹配结果ID',
            dataIndex: 'match_result_id',
            key: 'match_result_id',
            width: 100
        },
        {
            title: '数据ID',
            dataIndex: 'data_id',
            key: 'data_id',
            width: 80
        },
        {
            title: '操作',
            key: 'action',
            width: 80,
            render: (_, record) => (
                <Space size="small">
                    <Button
                        type="link"
                        size="small"
                        icon={<AimOutlined/>}
                        onClick={() => handleResultSelect(record)}
                    >
                        查看
                    </Button>
                </Space>
            )
        }
    ];

    return (
        <div className="matching-page">
            {/* 统计卡片 */}
            <Row gutter={16} style={{marginBottom: 24}}>
                <Col xs={24} sm={12} md={6}>
                    <Card>
                        <Statistic
                            title="总匹配数"
                            value={statistics.totalMatches}
                            prefix={<CheckCircleOutlined/>}
                            valueStyle={{color: '#1890ff'}}
                        />
                    </Card>
                </Col>
                <Col xs={24} sm={12} md={6}>
                    <Card>
                        <Statistic
                            title="已匹配数"
                            value={statistics.matchedShipments}
                            valueStyle={{color: '#52c41a'}}
                        />
                    </Card>
                </Col>
                <Col xs={24} sm={12} md={6}>
                    <Card>
                        <Statistic
                            title="未匹配数"
                            value={statistics.totalMatches - statistics.matchedShipments}
                            valueStyle={{color: '#faad14'}}
                        />
                    </Card>
                </Col>
                <Col xs={24} sm={12} md={6}>
                    <Card>
                        <Statistic
                            title="匹配率"
                            value={statistics.totalMatches > 0 ? (statistics.matchedShipments / statistics.totalMatches * 100).toFixed(1) : 0}
                            suffix="%"
                            valueStyle={{color: '#f5222d'}}
                        />
                    </Card>
                </Col>
            </Row>

            {/* 工具栏 */}
            <Card style={{marginBottom: 24}}>
                <div style={{
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                    flexWrap: 'wrap',
                    gap: '16px'
                }}>
                    <h3 style={{margin: 0}}>匹配结果</h3>
                    <Space>
                        <Input
                            placeholder="请输入数据ID (dataId)"
                            value={dataId}
                            onChange={(e) => setDataId(e.target.value)}
                            onPressEnter={handleSearch}
                            style={{width: 200}}
                        />
                        <Button
                            type="primary"
                            icon={<SearchOutlined/>}
                            onClick={handleSearch}
                            loading={loading}
                        >
                            查询
                        </Button>
                        <Button
                            type="primary"
                            icon={<ReloadOutlined/>}
                            onClick={handleRefresh}
                            loading={loading}
                            disabled={!dataId}
                        >
                            刷新
                        </Button>
                        <Button
                            icon={<ExportOutlined/>}
                            onClick={handleExport}
                            disabled={matchingResults.length === 0}
                        >
                            导出
                        </Button>
                    </Space>
                </div>
            </Card>

            {/* 详情区域 */}
            <Row gutter={16}>
                <Col span={12}>
                    <Card
                        title="匹配详情"
                        extra={
                            selectedResult && (
                                <Button
                                    type="text"
                                    onClick={() => setSelectedResult(null)}
                                >
                                    关闭
                                </Button>
                            )
                        }
                        style={{height: '600px', overflow: 'auto'}}
                    >
                        {selectedResult ? (
                            <div style={{padding: '16px 0'}}>
                                <Row gutter={16}>
                                    <Col span={12}>
                                        <strong>匹配详情ID:</strong>
                                        <div>{selectedResult.id}</div>
                                    </Col>
                                    <Col span={12}>
                                        <strong>匹配结果ID:</strong>
                                        <div>{selectedResult.matchResultId}</div>
                                    </Col>
                                </Row>

                                {/* 货物信息卡片 */}
                                <Card size="small" style={{marginTop: 16, backgroundColor: '#fff7e6'}}>
                                    <div style={{fontWeight: 'bold', marginBottom: 12, fontSize: '16px'}}>货物信息</div>
                                    <Row gutter={16}>
                                        <Col span={12}>
                                            <div>
                                                <div style={{fontSize: '14px', color: '#666'}}>货物ID</div>
                                                <div style={{fontSize: '18px', fontWeight: 'bold', color: '#1890ff'}}>
                                                    {selectedResult.shipmentId}
                                                </div>
                                            </div>
                                        </Col>
                                        <Col span={12}>
                                            <div>
                                                <div style={{fontSize: '14px', color: '#666'}}>数据ID</div>
                                                <div style={{fontSize: '18px', fontWeight: 'bold', color: '#1890ff'}}>
                                                    {selectedResult.dataId}
                                                </div>
                                            </div>
                                        </Col>
                                    </Row>
                                </Card>

                                {/* 路线信息卡片 */}
                                <Card size="small" style={{marginTop: 16, backgroundColor: '#f5f5f5'}}>
                                    <div style={{fontWeight: 'bold', marginBottom: 12, fontSize: '16px'}}>路线信息</div>
                                    <Row gutter={16}>
                                        <Col span={12}>
                                            <div>
                                                <div style={{fontSize: '14px', color: '#666'}}>路线ID</div>
                                                <div style={{
                                                    fontSize: '18px',
                                                    fontWeight: 'bold',
                                                    color: selectedResult.route_id ? '#52c41a' : '#faad14'
                                                }}>
                                                    {selectedResult.route_id || 'Self'}
                                                </div>
                                            </div>
                                        </Col>
                                        <Col span={12}>
                                            <div>
                                                <div style={{fontSize: '14px', color: '#666'}}>匹配状态</div>
                                                <div>
                                                    <Tag color={selectedResult.match_status === 1 ? 'green' : 'red'}
                                                         style={{fontSize: '14px'}}>
                                                        {selectedResult.match_status === 1 ? '已匹配' : '未匹配'}
                                                    </Tag>
                                                </div>
                                            </div>
                                        </Col>
                                    </Row>
                                </Card>

                                <Row gutter={16} style={{marginTop: 16}}>
                                    <Col span={24}>
                                        <strong>说明:</strong>
                                        <div style={{
                                            marginTop: 8,
                                            padding: '12px',
                                            backgroundColor: '#f0f2f5',
                                            borderRadius: '4px'
                                        }}>
                                            {selectedResult.routeId ? (
                                                <p style={{margin: 0, color: '#666'}}>
                                                    该货物已分配到路线ID为 <Tag
                                                    color="blue">{selectedResult.route_id}</Tag> 的路线。
                                                </p>
                                            ) : (
                                                <p style={{margin: 0, color: '#666'}}>
                                                    该货物未分配到任何路线（Self分配）。
                                                </p>
                                            )}
                                        </div>
                                    </Col>
                                </Row>
                            </div>
                        ) : (
                            <div style={{
                                display: 'flex',
                                flexDirection: 'column',
                                alignItems: 'center',
                                justifyContent: 'center',
                                height: '100%',
                                textAlign: 'center'
                            }}>
                                <CheckCircleOutlined style={{fontSize: 48, color: '#ccc', marginBottom: 16}}/>
                                <h3>选择匹配结果查看详情</h3>
                                <p style={{color: '#999'}}>点击下方表格中的"查看"按钮查看详情</p>
                            </div>
                        )}
                    </Card>
                </Col>

                <Col span={12}>
                    <Card title="匹配统计">
                        <div style={{padding: '16px 0'}}>
                            <Row gutter={16}>
                                <Col span={12}>
                                    <Statistic
                                        title="总匹配数"
                                        value={matchingResults.length}
                                        valueStyle={{color: '#1890ff'}}
                                    />
                                </Col>
                                <Col span={12}>
                                    <Statistic
                                        title="已匹配数"
                                        value={matchingResults.filter(m => m.match_status === 1).length}
                                        valueStyle={{color: '#52c41a'}}
                                    />
                                </Col>
                            </Row>
                            <Row gutter={16} style={{marginTop: 24}}>
                                <Col span={12}>
                                    <Statistic
                                        title="未匹配数"
                                        value={matchingResults.filter(m => m.match_status === 0).length}
                                        valueStyle={{color: '#f5222d'}}
                                    />
                                </Col>
                                <Col span={12}>
                                    <Statistic
                                        title="匹配率"
                                        value={matchingResults.length > 0 ? (matchingResults.filter(m => m.match_status === 1).length / matchingResults.length * 100).toFixed(1) : 0}
                                        suffix="%"
                                        valueStyle={{color: '#faad14'}}
                                    />
                                </Col>
                            </Row>
                        </div>
                    </Card>
                </Col>
            </Row>

            {/* 数据表格 */}
            <Card style={{marginTop: 24}}>
                <DataTable
                    title="匹配结果列表"
                    data={matchTable}
                    columns={columns}
                    loading={loading}
                    exportable
                    searchable
                    pagination
                    rowKey="id"
                    style={{marginTop: 16}}
                />
            </Card>
        </div>
    );
};

export default MatchingPage;